import type { TodoListType } from "@/hooks/model/todoModel"
import { defineStore } from "pinia"
import useLocalStoage from "../hooks/useLocalStoage"

let useTodoStore = defineStore("todomvc", {
  state: () => {
    return {
      visibility: "all",
      todoList: (useLocalStoage("todomvc").value || []) as TodoListType
      // todoList: [
      //   {
      //     id: "01",
      //     text: "学习vue3",
      //     done: true,
      //     isEdit: false
      //   },
      //   {
      //     id: "02",
      //     text: "学习react",
      //     done: false,
      //     isEdit: false
      //   }
      // ]
    }
  },
  getters: {
    // 判断是否都已完成
    isAllDone(this: {
      visibility: string;
      todoList: TodoListType;
  }) {
      return this.todoList.every(item => item.done === true)
    },
    // 统计没有完成的数量
    unDoneNumber(this:  {
      visibility: string;
      todoList: TodoListType;
  }) {
      return this.todoList.filter(item => item.done === false).length;
    },
    // 筛选出不同的todo
    filterTodoList(this: {todoList: TodoListType,visibility:string}) {
      if (this.visibility == "all") {
        return this.todoList
      } else if (this.visibility == "active") {
        return this.todoList.filter(item => item.done == false)
      } else if (this.visibility == "completed") {
        return this.todoList.filter(item => item.done == true)
      }
    }
  },
  actions: {
    // 删除某个todo
    del(index:number) {
      this.todoList.splice(index, 1)
    },
    // 改变单个todo的状态
    changeTodoStatus(idx:number, flag:boolean) {
      this.todoList[idx].done = flag;
    },
    // 全选与全不选
    changeAllTodoStatus(flag:boolean) {
      this.todoList.forEach(item => {
        item.done = flag;
      })
    },
    // 双击修改idEdit
    changeIsEdit(idx:number) {
      this.todoList[idx].isEdit = true;
    },
    // 结束编辑
    endEdit(idx:number, newText:string) {
      this.todoList[idx].text = newText.trim();
      this.todoList[idx].isEdit = false;
    },
    // 添加todo
    addTodo(newText:string) {
      this.todoList.push({
        id: Date.now().toString(),
        text: newText,
        done: false,
        isEdit: false
      })
    },
    // 改变visibility
    changeVisibility(vsb:string) {
      this.visibility = vsb;
    },
    // 删除已完成的todo
    delAllDone() {
      let res = this.todoList.filter(item => item.done == false);
      this.todoList.length = 0;
      this.todoList.push(...res)
    }
  }
})

export default useTodoStore